import React, { Component } from 'react'
import { connect } from "react-redux"
import styles from "./playingMusic.less"
import { getMusicUrl, getAlbumInfo, getArtistInfo, downloadFile} from "../../api/playingMusic"
import { Slider, message } from "antd"
import unknownArtistImg from "../../assets/image/unknownArtistImg.jpg"
import Icon from "../../components/icon/Icon"
import classNames from 'classnames'
import axios from 'axios';
@connect(
  (state) => ({
    PayingMusic: state.PayingMusic,
    musicList: state.musicList
  }),
  dispatch => ({
    setMusic: (info) => dispatch({ type: 'platingMusic/save', payload: info }),
    addMusicList: (info) => dispatch({ type: 'musicList/add', payload: { info } }),
    delMusicList: (index) => dispatch({ type: 'musicList/minus', payload: { index } }),
    addNextMusic: (payload) => dispatch({ type: 'musicList/addNextMusic', payload }),
  })
)
export default class PlayingMusic extends Component {
  state = {
    playingMusicUrl: null,
    sliderValue: 0,
    musicDuration: 0,
    playingDuration: 0,
    playing: false,
    downloadFileName: "",
    musicListHidden: true,
    musicListNone: true,
    musicListShow: false
  }
  componentDidMount() {
    // this.setPlayTime()
    
    document.body.onclick = () => {
      const { musicListShow } = this.state
      // 显示到隐藏aa
      if (musicListShow) {
        this.setState({
          musicListShow: false,
          musicListHidden: true
        })
        setTimeout(() => {
          this.setState({
            musicListNone: true
          })
        }, 400)
      }
    }
  }
  async componentDidUpdate(oldVal) {
    let { id: newId = null } = this.props.PayingMusic
    let { id: oldId = null } = oldVal.PayingMusic
    let { PayingMusic, musicList } = this.props
    // console.log("PayingMusic", PayingMusic);
    // console.log(newId, oldId);
    if(newId == null && oldId !== newId) {
      this.setState({
        playingMusicUrl: "",
        musicDuration: 0,
        downloadFileName: ""
      })
    }
    if (oldId !== newId && newId !== null) {
      let res = await getMusicUrl({ id: newId });
      let index = this.getPlayingIndex();
      if (index == -1) {
        this.props.addMusicList(this.props.PayingMusic)
      }
      let albumImg = null;
      if (PayingMusic && PayingMusic.album && PayingMusic.album.id) {
        let albumInfo = await getAlbumInfo({ id: PayingMusic.album.id });
        albumImg = albumInfo.album.picUrl
      }
      let musicInfo = { ...PayingMusic }
      // 专辑图片
      albumImg ? musicInfo.albumImgUrl = albumImg : null

      let artistsImg = null;
      if (PayingMusic && PayingMusic.artists[0] && PayingMusic.artists[0].id) {
        let artistsInfo = await getArtistInfo({ id: PayingMusic.artists[0].id });
        // console.log(artistsInfo);
        artistsImg = artistsInfo.data.artist.cover
      }
      // 歌手图片
      artistsImg ? musicInfo.artistsImgUrl = artistsImg : null
      this.props.setMusic(musicInfo);
      if(res[0].url) {
        this.setState({
          playingMusicUrl: res[0],
          musicDuration: this.props.PayingMusic.duration / 1000,
          downloadFileName: PayingMusic.name + "-" + PayingMusic.artists[0].name + "." + res[0].encodeType
        }, () => {
          this.audioDom.play();
        })
      }else {
        message.error("歌曲无法找到")
      }
    }
  }
  changeSliderValue = (value) => {
    const { musicDuration } = this.state
    this.setState({
      sliderValue: value
    })
    this.audioDom.currentTime = musicDuration / 100 * value
  }
  getAudio = (element) => {
    this.audioDom = element
  }
  setPlayTime = () => {
    this.time = setInterval(() => {
      // console.log(this.audioDom.currentTime);
      const { musicDuration } = this.state
      const playTime = this.audioDom.currentTime
      this.setState({
        playingDuration: playTime,
        sliderValue: parseInt(playTime / musicDuration * 100)
      })
    }, 500);
  }
  audioStopPlayMusic = () => {
    this.setState({
      playing: false
    })
    if (this.time) {
      clearInterval(this.time)
      this.time = null;
    }
  }
  audioPlayEnd = () => {
    const { musicList, setMusic, PayingMusic } = this.props
    this.setState({
      sliderValue: 100,
      playingDuration: this.state.musicDuration,
    })
    let index = this.getPlayingIndex() + 1
    if (index < musicList.length) {
      setMusic(musicList[index])
    } else {
      if(PayingMusic.id === musicList[0].id) {
        message.warning("列表只有这一首歌曲了哦，快点去添加吧！")
        this.audioDom.currentTime = 0
        this.audioDom.play()
      }else {
        setMusic(musicList[0])
      }
    }
  }

  getPlayingIndex = (PayingMusic = this.props.PayingMusic) => {
    const { musicList } = this.props
    let playIndex = -1;
    musicList.forEach((item, index) => {
      if (item.id === PayingMusic.id) {
        playIndex = index
      }
    })
    return playIndex
  }
  audioStartPlay = () => {
    this.setState({
      playing: true
    })
    if (this.time) {
      return
    }
    this.setPlayTime()
  }
  startMusic = () => {
    this.audioDom.play()
  }
  stopMusic = () => {
    this.audioDom.pause()
  }
  previousMusic = () => {
    const { musicList, setMusic, PayingMusic } = this.props
    let index = this.getPlayingIndex() - 1
    if (index >= 0) {
      setMusic(musicList[index])
    } else {
      if(PayingMusic.id === musicList[musicList.length - 1].id) {
        message.warning({content: "列表只有这一首歌曲了哦，不能换了", key: "更换歌曲失败"})
      }else {
        setMusic(musicList[musicList.length - 1])
      }
    }
  }
  nextMusic = () => {
    const { musicList, setMusic, PayingMusic } = this.props
    let index = this.getPlayingIndex() + 1
    if (index < musicList.length) {
      setMusic(musicList[index])
    } else {
      if(PayingMusic.id === musicList[0].id) {
        message.warning({content: "列表只有这一首歌曲了哦，不能换了", key: "更换歌曲失败"})
      }else {
        setMusic(musicList[0])
      }
    }
  }
  componentWillUnmount() {
    if (this.time) {
      clearInterval(this.time)
    }
  }
  downloadMusic = () => {
    // 创建隐藏的可下载链接
    const { playingMusicUrl, downloadFileName } = this.state
    if (playingMusicUrl && playingMusicUrl.url) {
      let downUrl = this.audioDom.src // 音乐地址 : 例如: http://m10.music.126.net/20201114948.mp3
      let fileName = downloadFileName // 文件名设置: 起风了.mp3
      message.success({content: "文件" + fileName + "开始下载， 请稍等。", key: fileName})
      downloadFile(downUrl, fileName)
    }
  }
  musicListHidden = (e) => {
    // musicListHidden: true,
    // musicListNone: true,
    // musicListShow: false
    e.stopPropagation();
    const { musicListShow, musicListHidden, musicListNone } = this.state

    // 显示到隐藏
    if (musicListShow) {
      this.setState({
        musicListShow: !musicListShow,
        musicListHidden: !musicListHidden
      })
      setTimeout(() => {
        this.setState({
          musicListNone: !musicListNone
        })
      }, 400)
    } else {
      // 隐藏到显示
      this.setState({
        musicListShow: !musicListShow,
        musicListNone: !musicListNone
      })
      setTimeout(() => {
        this.setState({
          musicListHidden: !musicListHidden
        })
      })
    }
  }
  setPayingMusic = (detail) => {
    this.props.setMusic(detail)
  }
  delMusic = (e, detail) => {
    e.stopPropagation();
    const {musicList} = this.props
    let index = this.getPlayingIndex(detail)
    let playIndex = this.getPlayingIndex();
    if(musicList.length <= 1) {
      message.warning({content: "列表只剩一首歌了，不能继续删除了。", key: "delMusic"})
      this.stopMusic()
    }else {
      if(playIndex == index) {
        this.props.delMusicList(index)
        this.nextMusic()
      }else {
        this.props.delMusicList(index)
      }
    }
  }
  addNextPlaying = (detail) => {
    let index = this.getPlayingIndex()
    let oldIndex = this.getPlayingIndex(detail)
    // console.log(index, oldIndex);
    if(index != -1, oldIndex != -1) {
      this.props.addNextMusic({index: index, oldIndex: oldIndex})
    }
  }
  render() {
    const { playingMusicUrl = {}, downloadFileName, sliderValue, playingDuration, musicDuration, playing, musicListHidden, musicListNone } = this.state
    const { PayingMusic, musicList } = this.props
    return (
      <div className={styles.playing_music}>
        <div className={styles.audio_box}>
          <audio id="mp3" ref={this.getAudio} className={styles.audio} src={playingMusicUrl && playingMusicUrl.url ? playingMusicUrl.url : null} onPlaying={this.audioStartPlay} onPause={this.audioStopPlayMusic} onEnded={this.audioPlayEnd}></audio>
        </div>
        <div className={styles.play_controls_box}>
          <div className={styles.slider_box}>
            <Slider value={sliderValue} tipFormatter={null} onChange={this.changeSliderValue} disabled={musicDuration == 0} />


          </div>
          <div className={styles.btn_box}>
            <div className={styles.btn_box_left}>
              <div className={styles.playing_music_img_box}>
                <img src={playingMusicUrl ? PayingMusic.albumImgUrl : unknownArtistImg} alt="" />
              </div>
              <div className={styles.music_info}>
                <div className={styles.music_info_name}>
                  {PayingMusic && PayingMusic.name ? PayingMusic.name : "未知"}
                </div>
                <div className={styles.music_info_artist}>
                  -
                  {PayingMusic && PayingMusic.artists && PayingMusic.artists.length > 0 ? PayingMusic.artists.map((artists, index) => (
                  <span key={index}> {artists.name} </span>
                )) : "未知"
                  }
                </div>
              </div>
              <div className={styles.download_btn} onClick={this.downloadMusic}> <Icon type="icon-xiazai" /> </div>
            </div>
            <div className={styles.btn_box_middle}>
              <div className={styles.play_previous} onClick={this.previousMusic}><Icon type="icon-shangyishou" /></div>
              {
                playing ?
                  <div onClick={this.stopMusic} className={classNames(styles.play_controls)} ><Icon type="icon-zanting1" /></div> :
                  <div onClick={this.startMusic} className={classNames(styles.play_controls, styles.padding_left)} ><Icon type="icon-bofang" /></div>
              }
              <div className={styles.play_next} onClick={this.nextMusic}><Icon type="icon-xiayishou" /></div>
            </div>
            <div className={styles.btn_box_right}>
              <div className={styles.playing_time}>
                {parseInt(playingDuration / 60) < 10 ? "0" + parseInt(playingDuration / 60) : parseInt(playingDuration / 60)}:
                {parseInt(playingDuration % 60) < 10 ? "0" + parseInt(playingDuration % 60) : parseInt(playingDuration % 60)} /
                {parseInt(musicDuration / 60) < 10 ? "0" + parseInt(musicDuration / 60) : parseInt(musicDuration / 60)}:
                {parseInt(musicDuration % 60) < 10 ? "0" + parseInt(musicDuration % 60) : parseInt(musicDuration % 60)}
              </div>
              <div className={styles.playing_music_list} onClick={this.musicListHidden}><Icon type="icon-songlist" /></div>
              <div className={classNames(styles.music_list_box, { [styles.hidden]: musicListHidden, [styles.display_none]: musicListNone })} onClick={(e) => {e.stopPropagation()}}>
                {
                  musicList.length > 0 ?
                  musicList.map(item => (
                    <div key={item.id} className={classNames(styles.music_list_data, {
                      [styles.music_list_playing]: (item.id == PayingMusic.id)
                    })}>
                      <div className={styles.music_list_info}>
                        <div className={styles.music_list_name}> {item.name}</div>
                        <div className={styles.music_list_artists}>{
                          item.artists.length > 0?
                          item.artists.map((artists, index) => (
                            <div key={index}>{artists.name} </div>
                          )): <span>"暂无" </span>
                        }</div>
                      </div>
                      <div className={styles.music_list_data_control}>
                        {item.id == PayingMusic.id ?
                          playing ?
                            (<div onClick={this.stopMusic} className={classNames(styles.music_list_btn)} ><Icon type="icon-zanting1" /></div> ):
                            (<div className={styles.music_list_btn} onClick={this.startMusic} ><Icon type="icon-bofang" /></div>) : null
                        }
                        {item.id != PayingMusic.id ?
                            (<div className={styles.music_list_btn} onClick={() => {this.setPayingMusic(item)}} ><Icon type="icon-bofang" /></div>): null
                        }
                        <div className={styles.music_list_btn} onClick={(e) => {this.delMusic(e, item)}}><Icon type="icon-lajitong" /></div>
                        {item.id != PayingMusic.id ?
                          <div className={styles.next_playing} onClick={() => {this.addNextPlaying(item)}}>下一首播放</div>
                          :null
                        }
                        {item.duration? 
                          <div className={styles.music_list_duration}>
                            {parseInt(item.duration / 1000 / 60) < 10 ? "0" + parseInt(item.duration / 1000 / 60) : parseInt(item.duration / 1000 / 60)}:
                            {parseInt(item.duration / 1000 % 60) < 10 ? "0" + parseInt(item.duration / 1000 % 60) : parseInt(item.duration / 1000 % 60)}
                          </div>
                          :null
                        }
                      </div>
                    </div>
                  )): <div className={styles.empty_list}>播放列表是空的呦！</div>
                }
              </div>
            </div>
          </div>
        </div>
      </div>
    )
  }
}
